package com.example.studentportrait.filter;

import com.example.studentportrait.domain.dto.LoginUser;
import com.example.studentportrait.utils.JwtUtil;
import com.example.studentportrait.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException,
            IOException {
        //获取token
        String token="";
        if(request.getHeader("sec-websocket-protocol")!=null){
            token=request.getHeader("sec-websocket-protocol");
        }
        else {
            token = request.getHeader("token");
        }
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userAccount;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userAccount = claims.getSubject();
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userAccount;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }//存入account
        redisCache.setCacheObject("account" , userAccount);
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        request.getSession().setAttribute("userAccount",userAccount);
        //放行
        filterChain.doFilter(request, response);
    }

//    @Autowired
//    RedisCache redisCache;
//
//    @Override
//    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws ServletException, IOException {
////        获取请求头的token
//        String token = req.getHeader("token");
//        if(!StringUtils.hasText(token)){
//            filterChain.doFilter(req,resp);
//            return;
//        }
////        解析token获得jwt令牌
//        Claims claims = null;
//        try {
//            claims = JwtUtil.parseJWT(token);
//        } catch (Exception e) {
//            e.printStackTrace();
////            token非法或超时
////            相应给前端需要重新登录
//            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//            WebUtils.renderString(resp, JSON.toJSONString(responseResult));
//            return;
//        }
//
////        根据token获取userId
//        String userAccount = claims.getSubject();
////        根据userId从redis中获取用户信息
//        LoginUser loginUser = redisCache.getCacheObject("login:" + userAccount);
////        获取不到用户信息
//        if(Objects.isNull(loginUser)){
////            登录过期，提示重新登录
//            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//            WebUtils.renderString(resp,JSON.toJSONString(responseResult));
//            return;
//        }
////        将用户信息存入存入SecurityContextHolder中
//        UsernamePasswordAuthenticationToken authenticationToken=new
//                UsernamePasswordAuthenticationToken(loginUser,null,null);
//        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        filterChain.doFilter(req,resp);
//    }
}
